package StudyCode.summary.myfile;

import java.io.*;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class DeserializingAnObject {
	public void m() {
		try {
			File file = new File("filename.ser");
			ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
			javax.swing.JButton button = (javax.swing.JButton) in.readObject();
			in.close();

			byte[] bytes = getBytesFromFile(file);

			in = new ObjectInputStream(new ByteArrayInputStream(bytes));
			button = (javax.swing.JButton) in.readObject();
			in.close();
		} catch (ClassNotFoundException | IOException ignored) {
		}
	}

	private static byte[] getBytesFromFile(File file) throws IOException {
		InputStream is = new FileInputStream(file);

		long length = file.length();


		byte[] bytes = new byte[(int) length];

		int offset = 0;
		int numRead = 0;
		while (offset < bytes.length
				&& (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
			offset += numRead;
		}

		if (offset < bytes.length) {
			throw new IOException("不能读取文件 " + file.getName());
		}

		is.close();
		return bytes;
	}
}
